local component = require("component")
local gpu = component.gpu

local bgColor = 0x00ffff
local fgColor = 0x888800
if gpu.getDepth() == 4 then bgColor = 0x6699ff end
local function vertical_line(x)
	gpu.fill(x,2,1,9,"│")
	gpu.set(x,1,"╤")
	gpu.set(x,11,"╧")
end
local function background(selected, buffer)
	local x,y = gpu.getResolution()
	local drawBuffer = buffer or gpu.allocateBuffer(x,11)
	local prevBuffer = gpu.getActiveBuffer()
	gpu.setActiveBuffer(drawBuffer)

	gpu.setBackground(bgColor)
	gpu.setForeground(fgColor)
	gpu.fill(1,1,x,y," ")
	gpu.fill(1,1,x,1,"═")
	gpu.fill(1,11,x,1,"═")
	gpu.fill(1,2,1,9,"║")
	gpu.fill(x,2,1,9,"║")
	gpu.set(1,1,"╔")
	gpu.set(x,1,"╗")
	gpu.set(1,11,"╚")
	gpu.set(x,11,"╝")

	local names = {
		{"Флеш Рояль", 800},
		{"Стрит-Флеш", 50},
		{"Каре", 25},
		{"Фулл-Хаус", 9},
		{"Флеш", 6},
		{"Стрит", 4},
		{"Сет", 3},
		{"Две пары", 2},
		{"Валет и выше", 1},
	}
	for i,v in ipairs(names) do
		gpu.set(2,1+i,v[1])
		for j=1,5 do
			if j == selected then
				gpu.setForeground(bgColor)
				gpu.setBackground(0x888800)
			end
			local value = v[2]*j*100
			if value >= 1000 then
				value = string.format("%4dK",(value//1000))
			else
				value = string.format("%5d",value)
			end
			gpu.set(15+(j*6),i+1,value)
			if j == selected then
				gpu.setBackground(bgColor)
				gpu.setForeground(0x888800)
			end
		end
	end
	for i=1,5 do
		vertical_line(14+(i*6))
	end

	gpu.setActiveBuffer(prevBuffer)
	return drawBuffer
end

local suits = {"♠","♡","♢","♣"}
local costs = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"," A"," 2"," 3"," 4"," 5"," 6"," 7"," 8"," 9","10"," J"," Q"," K"}

local function drawCard(buffer, symbol)
	local drawBuffer = buffer or gpu.allocateBuffer(7,7)
	local prevBuffer = gpu.getActiveBuffer()
	gpu.setActiveBuffer(drawBuffer)

	gpu.setForeground(0x000000)
	gpu.setBackground(bgColor)
	gpu.set(1,1,"▗")
	gpu.set(7,1,"▖")
	gpu.set(1,7,"▝")
	gpu.set(7,7,"▘")
	gpu.fill(2,1,5,1,"▄")
	gpu.fill(1,2,1,5,"▐")
	gpu.fill(2,7,5,1,"▀")
	gpu.fill(7,2,1,5,"▌")
	if symbol == nil then
		gpu.setBackground(0x660000)
		gpu.setForeground(0x006600)
		gpu.fill(2,2,5,5,"▚")
	else
		gpu.setBackground(0xffffff)
		gpu.fill(2,2,5,5," ")

		local suit = (symbol-1)//13+1
		local cost = (symbol-1)%13+1
		if suit == 2 or suit == 3 then
			gpu.setForeground(0xcc0000)
		else
			gpu.setForeground(0x000000)
		end
		gpu.set(4,4,suits[suit])
		gpu.set(2,2,costs[cost])
		gpu.set(5,6,costs[cost+13])
	end

	gpu.setActiveBuffer(prevBuffer)
	return drawBuffer
end

local function drawCenter(str, y)
	local x,_ = gpu.getResolution()
	local pos = (x-utf8.len(str))//2
	if pos < 0 then pos = 0 end
	gpu.set(pos,y,str)
end

return {
	background = background,
	card = drawCard,
	bgColor = bgColor,
	fgColor = fgColor,
	center = drawCenter
}
